﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using YJKRevitArea.ModifiedAreat;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;
using YJKArchBaseCode.OutWallSearch;
using YJKArchUtils.Utils;
using YJKRevitBase.WinForm;
using YJKRevitView;

namespace YJKRevitArea.AreaSet
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdInsideArea : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			CmdViewType types = CmdViewType.AreaPlan;
			try
			{
				if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
			}
			catch (Exception)
			{
				YJKMessageBox.Show("自动切换视图失败，请手动切换试图！");
				return Autodesk.Revit.UI.Result.Failed;
			}
			this.m_Revit = cmdData;
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			DialogResult dialogResult = DialogResult.Yes;
			HideWarningAndErroringKit @object = new HideWarningAndErroringKit(new List<string>
			{
				"CreateInsideArea"
			}, HideWarningAndErroringKit.HideKitEnum.HideWarning);
			cmdData.Application.Application.FailuresProcessing += @object.OnFailuresProcessing;
			if (CmdInsideArea._hWndRevit == null)
			{
				CmdInsideArea._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			}
			InsideAreaForm insideAreaForm = new InsideAreaForm(cmdData);
			insideAreaForm.Show(CmdInsideArea._hWndRevit);
			insideAreaForm.Refresh();
			int wMsg = 7;
			CmdInsideArea.SendMessage(CmdInsideArea._hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
			new OffsetWallLine(cmdData, "CenterLine");
			List<WallData> lstAllOutWall = new List<WallData>();
			OutWallFilter.Search(document, (document.ActiveView as ViewPlan).Id, ref lstAllOutWall, true, true);
			for (;;)
			{
				Dictionary<string, List<Room>> dictionary = this.GroupingRooms(document);
				if (dictionary.Count == 0)
				{
					break;
				}
				AreaCreator areaCreator = new AreaCreator(cmdData);
				if (DialogResult.Yes == dialogResult)
				{
					foreach (Area area in Common.FilterAreas(document))
					{
						Common.DeleteArea(document, area.Id);
					}
					using (Dictionary<string, List<Room>>.Enumerator enumerator2 = dictionary.GetEnumerator())
					{
						while (enumerator2.MoveNext())
						{
							KeyValuePair<string, List<Room>> keyValuePair = enumerator2.Current;
							List<Room> value = keyValuePair.Value;
							areaCreator.CreateInsideArea(document, value, insideAreaForm.m_labelInfo, insideAreaForm.m_RangeType, lstAllOutWall);
						}
						goto IL_1D0;
					}
					goto IL_1CE;
				}
				goto IL_1CE;
				IL_1D0:
				RoomFilter roomFilter = new RoomFilter();
				IList<Element> list = null;
				try
				{
					do
					{
						list = selection.PickElementsByRectangle(roomFilter, "请框选房间设置信息");
					}
					while (list.Count <= 0);
				}
				catch
				{
					if (insideAreaForm.m_reset)
					{
						insideAreaForm.m_reset = false;
						continue;
					}
					insideAreaForm.Close();
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				Transaction transaction = new Transaction(document, "SetRoomParameter");
				transaction.Start();
				foreach (Element element in list)
				{
					Room room = element as Room;
					this.SetRoomParameters(room, insideAreaForm.m_roomInfo);
				}
				transaction.Commit();
				continue;
				IL_1CE:
				dialogResult = DialogResult.Yes;
				goto IL_1D0;
			}
			YJKMessageBox.Show("请先使用房间编号功能设置房间的楼号户型等信息。");
			insideAreaForm.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void SetRoomParameters(Room room, RoomInfo roomParameter)
		{
			room.GetParameter("户型名称").Set(roomParameter.m_houseName);
			room.GetParameter("户型编号").Set(roomParameter.m_houseNum);
			room.GetParameter("单元").Set(roomParameter.m_unit);
			room.GetParameter("楼号").Set(roomParameter.m_buildingNum);
		}

		private Dictionary<string, List<Room>> GroupingRooms(Autodesk.Revit.DB.Document doc)
		{
			Dictionary<string, List<Room>> dictionary = new Dictionary<string, List<Room>>();
			foreach (Room room in Common.FilterRooms(doc))
			{
				try
				{
					string text = room.GetParameter("楼号").AsString().Trim();
					string text2 = room.GetParameter("单元").AsString().Trim();
					string text3 = room.GetParameter("户型名称").AsString().Trim();
					string text4 = room.GetParameter("户型编号").AsString().Trim();
					if (text3.Length != 0)
					{
						string key = string.Concat(new string[]
						{
							text,
							"_",
							text2,
							"_",
							text3,
							"_",
							text4
						});
						if (dictionary.ContainsKey(key))
						{
							dictionary[key].Add(room);
						}
						else
						{
							dictionary.Add(key, new List<Room>
							{
								room
							});
						}
					}
				}
				catch
				{
				}
			}
			return dictionary;
		}

		private bool GetRooms(ref List<Room> rooms)
		{
			IList<Reference> list = null;
			rooms.Clear();
			Selection selection = this.m_Revit.Application.ActiveUIDocument.Selection;
			try
			{
				list = selection.PickObjects((Autodesk.Revit.UI.Selection.ObjectType)1, new RoomsFilter(), "select rooms");
			}
			catch (Exception)
			{
				return false;
			}
			Document document = this.m_Revit.Application.ActiveUIDocument.Document;
			foreach (Reference reference in list)
			{
				Room room = document.GetElement(reference) as Room;
				if (room != null)
				{
					rooms.Add(room);
				}
			}
			return true;
		}

		private ExternalCommandData m_Revit;

        public static WindowHandle _hWndRevit;
	}
}
